import { ref, computed, Transition, reactive, onMounted, nextTick, onBeforeUnmount } from "vue";
import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import { useRoute } from "vue-router";
import { useRouter } from "vue-router";
import {
  GetCreditScoreUserGroupList
  , AddCreditScoreUserGroup, QueryCreditScoreCustomerInfo
} from "@/api/stu/bankBigData";
import { emitter } from "@/utils/mitt";
export function usePortrait() {
  const dataList = ref();
  const dataList2 = ref()
  const route = useRoute();
  const router = useRouter();
  const customerNameRegex = /^[\u4e00-\u9fa5a-zA-Z0-9]{4,15}$/ //检验4-15个字符并且不能重复
  const createTaskVisible = ref<boolean>(false);
  const loading = ref<boolean>(false);
  const formData = reactive({
    customerName: '',
  })
  const parameterValueMap = {
    1: ">",
    2: "=",
    3: "<",
    4: ">=",
    5: "<=",
    6: "≠",
  };
  const selectId = ref()
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    pageSizes: [5, 10, 15],
    background: true
  });
  const pagination2 = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    pageSizes: [5, 10, 15],
    background: true
  });

  const columns2: TableColumnList = [
    {
      label: "序号",
      type: "index",
    },
    {
      label: "姓名",
      prop: "name"
    }, {
      label: "年龄",
      prop: "age"
    }, {
      label: "性别",
      prop: "gender",
    }, {
      label: "工作类型",
      prop: "jobType"
    },
    {
      label: "是否按时还款",
      prop: "ontimeRepayment",
      minWidth: 150
    },
    {
      label: "还款频率",
      prop: "repaymentFrequency",
    }, {
      label: "是否有逾期或拖欠",
      prop: "isOverdue",
      minWidth: 150
    }, {
      label: "借款次数（次）",
      prop: "numberOfLoans",
      minWidth: 150,
    }, {
      label: "借款用途",
      prop: "loanPurposes"
    },
    {
      label: "信用卡使用频率",
      prop: "creditCardUseFrequency",
      minWidth: 150
    },
    {
      label: "借贷履约记录",
      prop: "lendingContractRecord",
      minWidth: 150,
    }, {
      label: "借款总额（万元）",
      prop: "totalLoanAmount",
      minWidth: 150,

    }, {
      label: "贷款余额（万元）",
      prop: "loanBalance",
      minWidth: 150,

    }, {
      label: "是否有催收记录",
      prop: "collectionRecord",
      minWidth: 150
    },
    {
      label: "恶意透支次数（次）",
      prop: "maliciousOverdraftTimes",
      minWidth: 150
    },
    {
      label: "近期是否有多次申请借贷",
      prop: "recentMultipleLoanApplications",
      minWidth: 200
    }, {
      label: "电信欠费频率",
      prop: "telecomOverdueFrequency",
      minWidth: 150
    }, {
      label: "是否在电信黑名单",
      prop: "blacklistStatus",
      minWidth: 150
    }, {
      label: "社保是否连续",
      prop: "continuousnessOverduePayments",
      minWidth: 150
    },
    {
      label: "是否存在断缴或缴费不足",
      prop: "paymentInterruptionsOrInsufficiencies", minWidth: 250
    },
    {
      label: "不动产",
      prop: "realEstate",
    }, {
      label: "证券（万元）",
      prop: "securities",
      minWidth: 150,

    }, {
      label: "基金（万元）",
      prop: "funds",
      minWidth: 150,

    }, {
      label: "保险（万元）",
      prop: "insurance",
      minWidth: 150,

    },
    {
      label: "现金（万元）",
      prop: "cash",
      minWidth: 150,

    },
    {
      label: "变现能力",
      prop: "liquidity"
    }, {
      label: "信用飞违约次数（次）",
      prop: "defaultTime",
      minWidth: 200
    }, {
      label: "是否在航旅黑名单",
      prop: "isblacklist",
      minWidth: 200
    },
    {
      label: "已取得的最高学历",
      prop: "educationLevel",
      minWidth: 200
    },
    {
      label: "有无继续教育打算",
      prop: "continuingEducationWillingness",
      minWidth: 200
    }, {
      label: "社交活跃度",
      prop: "socialActivity"
    }, {
      label: "网购频率",
      prop: "onlineShoppingFrequency",
    }, {
      label: "游戏时长",
      prop: "gamingHours"
    },
    {
      label: "是否有固定的工作",
      prop: "employmentStatus",
      minWidth: 200
    }, {
      label: "是否有其他稳定收入",
      prop: "additionalIncome",
      minWidth: 200
    },
    {
      label: "月收入（元）",
      prop: "monthlyIncome",
      minWidth: 150,

    },
  ];
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      width: 120
    }, {
      label: "客群名称",
      prop: "customerGroupName"
    }, {
      label: "筛选条件",
      prop: "screeningCondition",
    },
    {
      label: "操作",
      prop: "operation",
      width: 180,
      slot: "operation"
    },
  ];
  const BtnLoading = ref<boolean>(false)
  function OUTBtnLoding() {
    setTimeout(() => {
      BtnLoading.value = false
    }, 1000)
  }
  const handleCurrentChange = val => {
    getList()
  };
  function handleSizeChange() {
    getList()
  }
  //获取选中列表下的人数
  async function getList2() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: pagination2.currentPage,
      pageCount: pagination2.pageSize,
      detailId: selectId.value,
    };
    let res = await QueryCreditScoreCustomerInfo(data)
    if (res.success) {
      dataList2.value = res?.data.items
      pagination2.total = res?.data.totalCount
    } else {
      ElMessage.error(res.msg);
    }

  }
  const handleCurrentChange2 = val => {
    getList2()
  };
  function handleSizeChange2() {
    getList2()
  }


  function saveCreate() {
    if (customerNameRegex.test(formData.customerName) === false) {
      ElMessage({
        showClose: false,
        message: '客群名称应该请输4 - 15个字符',
        type: 'warning',
        duration: 1000,
      })
      return
    }
    BtnLoading.value = true
    OUTBtnLoding()
    emitter.emit("CustomerGroupScreening")
  }

  onBeforeUnmount(() => {
    emitter.off("CustomerGroupScreeningSave")
  })
  //创建任务
  emitter.on("CustomerGroupScreeningSave", async (row) => {
    const data = JSON.parse(row)
    const resultParams = {
      planId: route.query.planId,
      taskId: route.query.taskId,
      customerGroupName: formData.customerName,
      customerScreening: []
    }
    data.forEach(item => {
      const outerLayerId = item['id'][0];
      const isPresent = resultParams.customerScreening.find(obj => obj.id == outerLayerId);

      if (isPresent) {
        addToOperatorsInfoList(isPresent.operatorsInfoList, item);
      } else {
        const outerLayer = {
          id: outerLayerId,
          operatorsInfoList: []
        };
        addToOperatorsInfoList(outerLayer.operatorsInfoList, item);
        resultParams.customerScreening.push(outerLayer);
      }
    });
    const json = {
      customerGroupName: resultParams.customerGroupName,
      customerScreening: resultParams.customerScreening,
    }
    resultParams.studentAnswer = JSON.stringify(json)
    resultParams.customerScreening.forEach(obj => {
      delete obj.id;
    });
    let res = await AddCreditScoreUserGroup(resultParams)
    if (res.status == 200) {
      ElMessage.success(res.msg);
      createTaskVisible.value = false
      for (let variable in formData) {
        formData[variable] = '';
      }
      getList()
    } else {
      ElMessage.error(res.msg);
    }
  })

  //解析多层筛选数据
  function addToOperatorsInfoList(operatorsInfoList, item) {
    if (item.mType == 3) {
      operatorsInfoList.push({
        "fieldName": item.mName,
        "fieldType": 1,
        "operatorsList": [
          {
            "parameterValue": item.selectMore.join('|'),
            "operatorsStr": item.rather == 1 ? '包含' : '不包含'
          }
        ]
      })
    } else {
      operatorsInfoList.push({
        "fieldName": item.term,
        "fieldType": 2,
        "operatorsList": [
          {
            "parameterValue": Number(item.times),
            "operatorsStr": parameterValueMap[item.rather]
          },
          {
            "parameterValue": Number(item.times2),
            "operatorsStr": parameterValueMap[item.rather2],
          },
        ]
      })
    }
  }

  //获取任务列表
  async function getList() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
    };
    const respone = await GetCreditScoreUserGroupList(data);
    if (respone.success) {
      dataList.value = respone?.data.items
      pagination.total = respone.data.totalCount;
    } else {
      ElMessage.error(respone.msg);
    }
  }

  //点击查看详情更新子列表
  async function checkPor(row) {
    selectId.value = row.creditScoreUserGroupId
    getList2()
  }
  onMounted(async () => {
    getList()
  })
  return {
    columns,
    loading,
    dataList,
    dataList2,
    pagination,
    pagination2,
    columns2,
    formData,
    createTaskVisible,
    handleSizeChange,
    handleCurrentChange,
    handleSizeChange2,
    handleCurrentChange2,
    checkPor,
    saveCreate,
    BtnLoading
  }
}